import { useState, useRef, useEffect } from 'react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';

export default function RandomNamePicker() {
  // 初始名单
  const initialNames = "张三、李四、王五、赵六、孙七、周八、吴九、郑十、陈晨、刘洋";
  
  // 状态管理
  const [nameList, setNameList] = useState(initialNames);
  const [excludeDuplicates, setExcludeDuplicates] = useState(false);
  const [drawnNames, setDrawnNames] = useState<string[]>([]);
  const [currentName, setCurrentName] = useState<string | null>(null);
  const [isDrawing, setIsDrawing] = useState(false);
  
  // 动画相关引用
  const resultRef = useRef<HTMLDivElement>(null);
  
  // 解析名字列表
  const parseNames = (text: string): string[] => {
    return text
      .split('、')
      .map(name => name.trim())
      .filter(name => name.length > 0);
  };
  
  // 抽取随机名字
  const drawRandomName = () => {
    const names = parseNames(nameList);
    
    if (names.length === 0) {
      toast.error('请先输入名字列表');
      return;
    }
    
    // 如果启用不重复且所有名字都已抽取，则重置
    if (excludeDuplicates && drawnNames.length >= names.length) {
      toast.info('所有名字已抽取完毕，将重置抽取记录');
      setDrawnNames([]);
    }
    
    // 过滤可抽取的名字
    const availableNames = excludeDuplicates 
      ? names.filter(name => !drawnNames.includes(name))
      : names;
    
    if (availableNames.length === 0) {
      toast.error('没有可抽取的名字了');
      return;
    }
    
    // 开始抽取动画
    setIsDrawing(true);
    setCurrentName(null);
    
    // 短暂延迟后显示结果，增强随机感
    setTimeout(() => {
      const randomIndex = Math.floor(Math.random() * availableNames.length);
      const selectedName = availableNames[randomIndex];
      
      setCurrentName(selectedName);
      
      // 如果启用不重复，添加到已抽取列表
      if (excludeDuplicates && !drawnNames.includes(selectedName)) {
        setDrawnNames(prev => [...prev, selectedName]);
      }
      
      setIsDrawing(false);
    }, 800);
  };
  
  // 重置抽取状态
  const resetDrawing = () => {
    setDrawnNames([]);
    setCurrentName(null);
    toast.success('已重置抽取记录');
  };
  
  // 添加结果动画效果
  useEffect(() => {
    if (currentName && resultRef.current) {
      // 添加动画类
      resultRef.current.classList.add('animate-bounce-in');
      
      // 动画结束后移除类
      const timer = setTimeout(() => {
        if (resultRef.current) {
          resultRef.current.classList.remove('animate-bounce-in');
        }
      }, 1000);
      
      return () => clearTimeout(timer);
    }
  }, [currentName]);
  
  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-2xl mx-auto w-full">
        {/* 标题区域 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-slate-800 dark:text-white mb-2">随机抽取工具</h1>
          <p className="text-slate-600 dark:text-slate-400">公平、随机地从名单中抽取人员</p>
        </div>
        
        {/* 主内容卡片 */}
        <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl overflow-hidden transition-all duration-300 hover:shadow-2xl">
          {/* 名单输入区域 */}
          <div className="p-6 border-b border-slate-200 dark:border-slate-700">
            <label htmlFor="nameList" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
              名单（使用中文逗号“、”分隔）
            </label>
            <textarea
              id="nameList"
              value={nameList}
              onChange={(e) => setNameList(e.target.value)}
              className="w-full h-32 p-3 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-slate-700 dark:text-white transition-all"
              placeholder="请输入名字，使用中文逗号“、”分隔"
            />
          </div>
          
          {/* 控制区域 */}
          <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex flex-col sm:flex-row gap-4 items-center justify-between">
            <div className="flex items-center">
              <input
                type="checkbox"
                id="excludeDuplicates"
                checked={excludeDuplicates}
                onChange={(e) => setExcludeDuplicates(e.target.checked)}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-slate-300 dark:border-slate-600 rounded"
              />
              <label htmlFor="excludeDuplicates" className="ml-2 block text-sm text-slate-700 dark:text-slate-300">
                不允许重复抽取
              </label>
            </div>
            
            <div className="flex gap-3 w-full sm:w-auto">
              <button
                onClick={resetDrawing}
                disabled={drawnNames.length === 0 && !currentName}
                className="flex-1 sm:flex-none px-4 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm font-medium text-slate-700 dark:text-slate-300 bg-white dark:bg-slate-700 hover:bg-slate-50 dark:hover:bg-slate-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                重置
              </button>
              
              <button
                onClick={drawRandomName}
                disabled={isDrawing}
                className="flex-1 sm:flex-none px-6 py-2 bg-blue-600 border border-transparent rounded-lg text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all disabled:opacity-80"
              >
                {isDrawing ? '抽取中...' : '抽取'}
              </button>
            </div>
          </div>
          
          {/* 结果展示区域 */}
          <div className="p-6 flex flex-col items-center justify-center min-h-40">
            {currentName ? (
              <div 
                ref={resultRef}
                className="text-center"
                style={{
                  animation: isDrawing ? 'nameRoll 0.8s linear' : 'none'
                }}
              >
                <p className="text-sm text-slate-500 dark:text-slate-400 mb-2">本次抽取结果</p>
                <div className="text-4xl font-bold text-blue-600 dark:text-blue-400 tracking-tight">
                  {currentName}
                </div>
              </div>
            ) : (
              <div className="text-center">
                <div className="w-16 h-16 bg-slate-100 dark:bg-slate-700 rounded-full flex items-center justify-center mx-auto mb-4">
                  <i className="fa-solid fa-hand-pointer text-slate-400 text-2xl"></i>
                </div>
                <p className="text-slate-500 dark:text-slate-400">
                  点击"抽取"按钮开始随机选择名字
                </p>
              </div>
            )}
            
            {/* 已抽取名单 */}
            {drawnNames.length > 0 && (
              <div className="mt-6 w-full">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">已抽取：</p>
                <div className="flex flex-wrap gap-2">
                  {drawnNames.map((name, index) => (
                    <span 
                      key={index}
                      className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 dark:bg-slate-700 text-slate-800 dark:text-slate-200"
                    >
                      {name}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
        
        {/* 说明文字 */}
        <p className="mt-4 text-xs text-center text-slate-500 dark:text-slate-400 max-w-md mx-auto">
          提示：名单中的名字请使用中文逗号“、”分隔，如"张三、李四、王五"
        </p>
      </div>
    </div>
  );
}

// 添加自定义动画
const style = document.createElement('style');
style.textContent = `
  @keyframes nameRoll {
    0% { transform: scale(0.5); opacity: 0; }
    20% { transform: scale(1.2); opacity: 0.8; }
    40% { transform: scale(0.9); opacity: 1; }
    60% { transform: scale(1.1); opacity: 1; }
    80% { transform: scale(0.95); opacity: 1; }
    100% { transform: scale(1); opacity: 1; }
  }
  
  .animate-bounce-in {
    animation: nameRoll 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  }
`;
document.head.appendChild(style);